﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.Reflection;
using System.Configuration;
using System.ServiceModel.Description;
using NLog;

namespace WcfHost {
	class ServiceWrapper {

		private List<ServiceHost> _hosts = new List<ServiceHost>();
		private static Logger logger = LogManager.GetCurrentClassLogger(); 

		internal void StartServices() {
			logger.Info("Starter services ....");
			// Get the list of services to run
			WcfServiceConfigurationSection configServices = ConfigurationManager.GetSection("serviceSettings") as WcfServiceConfigurationSection;
			if (configServices == null) {
				throw new ConfigurationErrorsException("Kunne ikke finde \"ServiceSettings\" i configurations filen");
			}
			// Instantiate all defindes services by first loading the assembly and then creating the servicehost
			foreach (ServiceConfigurationElement serviceElement in configServices.Services) {
				// Get the service host type
				Type serviceType = Type.GetType(serviceElement.ServiceType, true, true);
				if (serviceType == null) {
					throw new TypeLoadException("Kunne ikke loade typen " + serviceElement.ServiceType + "'.");
				}

				// Open the host
				ServiceHost host = new ServiceHost(serviceType);
				host.Open();

				// Add the host to the list of opened hosts
				_hosts.Add(host);
			}
		}

		/// <summary>
		/// Stops all configured services.
		/// </summary>
		internal void StopServices() {
			logger.Info("Stopper services ....");
			foreach (ServiceHost host in _hosts) {
				try {
					if (host != null)
						host.Close();
				}
				catch (Exception ex) {
					WcfHostApp.LogOutput(ex.Message);
					// if this guy wont stop we still need to stop the others
				}
			}
		}


		public override string ToString() {

			StringBuilder builder = new StringBuilder();

			foreach (ServiceHost host in _hosts) {

				builder.Append("\t").AppendLine(host.Description.ConfigurationName);

				foreach (ServiceEndpoint endPoint in host.Description.Endpoints) {
					builder.Append("\t\tEndpoint :").AppendLine(endPoint.ListenUri.ToString());
				}

				builder.Append(Environment.NewLine);
			}
			return builder.ToString();
		}

	}
}
